package com.xjy.spring.memcached.xm;

import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xjy.spring.memcached.core.MemcachedConnection;


public class XMemcachedConnection implements MemcachedConnection {
	private static final Logger LOGGER = LoggerFactory.getLogger(XMemcachedConnection.class);
	private MemcachedClient connection;
	public XMemcachedConnection() {
	}
	
	public XMemcachedConnection(MemcachedClient connection) {
		super();
		this.connection = connection;
	}

	@Override
	public <T> boolean set(String key, int exp, T value) {
		try {
			return connection.set(key, exp, value);
		} catch (InterruptedException | TimeoutException | MemcachedException e) {
			LOGGER.error("Use XMemcachedConnection, operation is set, key is " + key + ", value is " + value + ",exp is" + exp, e);
		}
		return false;
	}

	@Override
	public MemcachedClient getNativeConnection() {
		return connection;
	}

	@Override
	public <T> T get(String key) {
		try {
			return connection.get(key);
		} catch (TimeoutException | InterruptedException | MemcachedException e) {
			LOGGER.error("Use XMemcachedConnection, operation is get, key is " + key, e);
		}
		return null;
	}

	@Override
	public boolean delete(String key) {
		try {
			return connection.delete(key);
		} catch (TimeoutException | InterruptedException | MemcachedException e) {
			LOGGER.error("Use XMemcachedConnection, operation is delete, key is " + key, e);
		}
		return false;
	}

}
